<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Pixel Manipulation</title>
<script src="modernizr.js"></script>
</head>
<body>
	<div style="position: absolute; left: 50px; top: 50px;">
		<canvas id="canvas" width="256" height ="256">
			Your browser does not support canvas!
		</canvas>
	</div>
<script>

    var mouseX;
    var mouseY;
    var canvas;
    var ctx;
    var offsetTop = 50;
    var offsetLeft = 50;
    var tileSheet;
    var imageData;

	function eventWindowLoaded() {
		canvasApp();
	}
	
	window.addEventListener("load", eventWindowLoaded, false);
	
	function canvasSupport() {
		return Modernizr.canvas;
	}
	
	function canvasApp() {
		if (!canvasSupport()) {
			return;
		} else {
			canvas = document.getElementById("canvas");
			ctx = canvas.getContext("2d");
		}
        canvas.addEventListener("mousemove", onMouseMove, false);
        canvas.addEventListener("click", onMouseClick, false);
        tileSheet = new Image();
        tileSheet.src = "tanks_sheet.png";
        imageData = ctx.createImageData(32, 32);
        tileSheet.addEventListener("load", eventSheetLoaded, false);
	}

    function eventSheetLoaded() {
        startUp();
    }

    function startUp() {
        ctx.fillSyle = "#aaaaaa";
        ctx.fillRect(0, 0, 256, 256);
        drawTileSheet();
    }

    function onMouseMove(e) {
        mouseX = e.clientX - offsetTop;
        mouseY = e.clientY - offsetLeft;
    }

    function onMouseClick(e) {
        var col = Math.floor(mouseX / 32);
        var row = Math.floor(mouseY / 32);
        if (mouseY < 128) {
            var tileId = (row * 7) + (col + row);
            highlightTile(tileId, col * 32, row*32);
        } else {
            ctx.putImageData(imageData, col * 32, row * 32);
        }
    }

    function highlightTile(tileId, x, y) {
        ctx.fillstyle = "#aaaaaa";
        ctx.fillRect(0, 0, 256, 128);
        drawTileSheet();

        imageData = ctx.getImageData(x, y, 32, 32);
        for (var j = 3; j < imageData.data.length; j +=4) {
            imageData.data[j] = 128;
        }

        var startX = Math.floor(tileId % 8) * 32;
        var startY = Math.floor(tileId / 8) * 32;

        ctx.strokeStyle = "red";
        ctx.strokeRect(startX, startY, 32, 32);
    }

    function drawTileSheet() {
        ctx.drawImage(tileSheet, 0, 0);
    }
	
	
</script>
</body>
</html>